package com.myexample.computerinternetdemo.model.impl;

import com.myexample.computerinternetdemo.model.IConnect;
import com.myexample.computerinternetdemo.util.CloseUtil;
import com.myexample.computerinternetdemo.util.MyInfo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class ClientConnect implements IConnect {
    private Socket socket = null;

    @Override
    public void connected(String ip) {
        if (socket == null || socket.isClosed()) {
            try {
                socket = new Socket(ip, MyInfo.PORT);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public boolean isConnected() {
        return socket != null && !socket.isClosed();
    }

    @Override
    public String getTextFromServer() {
        StringBuilder builder = new StringBuilder();
        if (socket != null&&!socket.isClosed()&&!socket.isInputShutdown() ) {
            InputStream inputStream = null;
            try {
                inputStream = socket.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String str = null;

            while (true) {
                try {
                    if ((str = reader.readLine()) == null)
                        break;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                builder.append(str).append("\n");
            }
            //尝试shutdownInput
            try {
                socket.shutdownInput();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return builder.toString();
    }

    @Override
    public void sendTextToServer(String text) {
        if (!socket.isClosed() && socket != null&&!socket.isOutputShutdown()) {
            OutputStream outputStream = null;
            try {
                outputStream = socket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            PrintWriter out = new PrintWriter(new OutputStreamWriter(outputStream));
            out.write(text);
            out.flush();

            //尝试shutdoutput
            try {
                socket.shutdownOutput();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void close() {
        CloseUtil.doClose(socket);
    }

}
